package com.xdap.keymen.service.punch;

import com.definesys.mpaas.query.MpaasQuery;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.xdap.keymen.config.PunchConfig;
import com.xdap.keymen.entity.*;
import com.xdap.keymen.service.dayang.BaseService;
import com.xdap.keymen.utils.OKHttpUtils;
import com.xdap.motor.entity.SnowflakeIdWorker;
import com.xdap.motor.vo.ResponseVo;
import com.xdap.runtime.service.RuntimeAppContextService;
import com.xdap.runtime.service.RuntimeDatasourceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
@Slf4j
public class PunchService  {
    private final RuntimeDatasourceService runtimeDatasourceService;
    private final RuntimeAppContextService runtimeAppContextService;
    private final SnowflakeIdWorker snowflakeIdWorker;

    private final PunchConfig punchConfig;

    @Autowired
    OKHttpUtils okHttpUtils;

    /**
     * 获取客户总数
     * @param rv
     * @return
     */
    public int countCustomers(Long rv) {
        int count=0;
        Gson gson = new GsonBuilder().create();
        Map<String, String> params=new HashMap<>();
        Map<String, String> headers=new HashMap<>();
        String response = okHttpUtils.doGet(punchConfig.getUrl().concat("/CRM/api/Customer/Count/"+rv.toString()), params,headers);
        PunchResponse punchResponse = gson.fromJson(response, new TypeToken<PunchResponse>(){}.getType());
        count=Integer.parseInt(punchResponse.getResult());
        return count;
    }

//
//    /**
//     * 获取客户列表
//     * @param rv
//     * @return
//     */
//    public ResponseVo getCustomerList(Long rv) {
//        //为空则到表中取
//        if (rv==null) {
//            //2=punch_sales_order
//            rv=getMaxRvid("2");
//        }
//        Gson gson = new GsonBuilder().create();
//        Map<String, String> params=new HashMap<>();
//        Map<String, String> headers=new HashMap<>();
//        //每页条数
//        int sz=100;
//        //页面
//        int pg=1;
//        //记录总数
//        int maxCount=this.countCustomers(rv);
//        log.info("最大记录数maxCount:{}",maxCount);
//        //测试，先默认
//        maxCount=130;
//        // 计算总页数 (向上取整)
//        int totalPages = (int) Math.ceil((double) maxCount / sz);
//        for (int currentPage = pg; currentPage <= totalPages; currentPage++) {
//
//            String response = okHttpUtils.doGet(punchConfig.getUrl().concat("/CRM/api/CO/")+rv.toString()+"/"+sz+"/"+currentPage, params,headers);
//            PunchResponse punchResponse = gson.fromJson(response, new TypeToken<PunchResponse>(){}.getType());
//
//            List<PunchOrderResponseEntity> list = gson.fromJson(punchResponse.getResult(), new TypeToken<List<PunchOrderResponseEntity>>(){}.getType());
//            for(PunchOrderResponseEntity PunchOrderResponseEntity:list){
//                //saveOrUpdateCustomer(punchSalesClientResponseEntity);
//            }
//
//            // 如果已经是最后一页，退出循环
//            if (currentPage == totalPages) {
//                break;
//            }
//        }
//
//        return ResponseVo.ok().setData(maxCount);
//    }

    /**
     * 获取最大的rvid
     * @param rvidTable
     * @return
     */
    public Long getMaxRvid(String rvidTable) {
        Long maxRvid = 0L;
        String tableName="punch_sales_client";
        if(rvidTable.equals("1")){
            tableName="punch_sales_client";
        }else if (rvidTable.equals("2")){
            tableName="punch_sales_order";
        }else if (rvidTable.equals("3")){
            tableName="punch_sales_order_product";
        }
        String currentTenantId = runtimeAppContextService.getCurrentTenantId();
        MpaasQuery query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
        query.sql("select IF(ISNULL(max(rvid)),0,max(rvid)) as rvid from "+tableName+";");
        Long l= query.doQueryFirst(Long.class);
        if (l!=null) {
            maxRvid=l;
        }
        return maxRvid;
    }

//    private void insertCustomer(PunchSalesClientResponseEntity punchSalesClientResponseEntity) {
//        PunchSalesClientEntity entity = new PunchSalesClientEntity();
//        entity.setId(snowflakeIdWorker.nextId());
//        entity.setDocumentId(snowflakeIdWorker.nextId());
//        entity.setClientName(punchSalesClientResponseEntity.getContact_co());
//        entity.setClientNumber(punchSalesClientResponseEntity.getCust_num());
//        entity.setRvid(punchSalesClientResponseEntity.getRvid());
//        String currentTenantId = runtimeAppContextService.getCurrentTenantId();
//        MpaasQuery query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
//        query.doInsert(entity);
//    }

//    private void saveOrUpdateCustomer(PunchSalesClientResponseEntity punchSalesClientResponseEntity) {
//        String currentTenantId = runtimeAppContextService.getCurrentTenantId();
//        MpaasQuery query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
//        query.sql("select id from punch_sales_client where client_number="+punchSalesClientResponseEntity.getCust_num());
//        String id= query.doQueryFirst(String.class);
//        if (id!=null) {
//            //更新
////            query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
////            query.update("client_name",punchSalesClientResponseEntity.getContact_co());
////            query.update("rvid",punchSalesClientResponseEntity.getRvid());
////            query.eq("client_number", punchSalesClientResponseEntity.getCust_num());
////            query.doUpdate(PunchSalesClientEntity.class);
//        }else{
//            //新增
////            PunchSalesClientEntity entity = new PunchSalesClientEntity();
////            entity.setId(snowflakeIdWorker.nextId());
////            entity.setDocumentId(snowflakeIdWorker.nextId());
////            entity.setClientName(punchSalesClientResponseEntity.getContact_co());
////            entity.setClientNumber(punchSalesClientResponseEntity.getCust_num());
////            entity.setRvid(punchSalesClientResponseEntity.getRvid());
////            query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
////            query.doInsert(entity);
//        }
//
//    }


//    public ResponseVo getOrderList(Long rv) {
//        //为空则到表中取
//        if (rv==null) {
//            //1=punch_sales_client
//            rv=getMaxRvid("2");
//        }
//        Gson gson = new GsonBuilder().create();
//        Map<String, String> params=new HashMap<>();
////        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
////        params.put("startDate", startDate);
////        params.put("endDate",endDate);
//        Map<String, String> headers=new HashMap<>();
//        //每页条数
//        int sz=100;
//        //页面
//        int pg=1;
//        //记录总数
//        int maxCount=this.countOrders(rv);
//        log.info("最大记录数maxCount:{}",maxCount);
//        //测试，先默认
//        maxCount=130;
//        // 计算总页数 (向上取整)
//        int totalPages = (int) Math.ceil((double) maxCount / sz);
//        for (int currentPage = pg; currentPage <= totalPages; currentPage++) {
//            //https://pisi.punch.com.cn:8498/CRM/api/CO/{rv}/{sz}/{pg}
//            String response = okHttpUtils.doGet(punchConfig.getUrl().concat("/CRM/api/CO/"+rv.toString()+"/"+sz+"/"+currentPage), params,headers);
//            PunchResponse punchResponse = gson.fromJson(response, new TypeToken<PunchResponse>(){}.getType());
//            String result =punchResponse.getResult();
//            List<PunchOrderResponseEntity> list = gson.fromJson(punchResponse.getResult(), new TypeToken<List<PunchOrderResponseEntity>>(){}.getType());
//            for(PunchOrderResponseEntity punchOrderResponseEntity:list){
//                saveOrUpdateOrder(punchOrderResponseEntity);
//            }
//
//            // 如果已经是最后一页，退出循环
//            if (currentPage == totalPages) {
//                break;
//            }
//        }
//
//        return ResponseVo.ok().setData(maxCount);
//    }
//


//    private void saveOrUpdateOrder(PunchOrderResponseEntity entity) {
//        String currentTenantId = runtimeAppContextService.getCurrentTenantId();
//        MpaasQuery query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
//        query.sql("select id from punch_sales_order where sales_order_number='"+entity.getCo_num()+"'");
//        String id= query.doQueryFirst(String.class);
//        if (id!=null) {
//            //更新
//            query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
//            query.update("client_name",StringUtils.strip(entity.getContact_co()));
//            query.update("client_number",StringUtils.strip(entity.getCust_num()));
//            query.update("rvid",entity.getRvid());
//            query.update("last_update_date",new Date());
//            query.eq("sales_order_number", entity.getCo_num());
//            query.doUpdate(PunchOrderEntity.class);
//        }else{
//            //新增
//            PunchOrderEntity punchOrderEntity = new PunchOrderEntity();
//            punchOrderEntity.setId(snowflakeIdWorker.nextId());
//            punchOrderEntity.setDocumentId(snowflakeIdWorker.nextId());
//            punchOrderEntity.setClientName(StringUtils.strip(entity.getContact_co()));
//            punchOrderEntity.setSalesOrderNumber(StringUtils.strip(entity.getCo_num()));
//            punchOrderEntity.setClientNumber(StringUtils.strip(entity.getCust_num()));
//            punchOrderEntity.setRvid(entity.getRvid());
//            query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
//            query.doInsert(punchOrderEntity);
//        }
//
//    }



//    public int countOrders(Long rv) {
//        int count=0;
//        Gson gson = new GsonBuilder().create();
//        Map<String, String> params=new HashMap<>();
//        Map<String, String> headers=new HashMap<>();
//        //https://pisi.punch.com.cn:8498/CRM/api/CO/Count/{rv}
//        String response = okHttpUtils.doGet(punchConfig.getUrl().concat("/CRM/api/CO/Count/"+rv.toString()), params,headers);
//        PunchResponse punchResponse = gson.fromJson(response, new TypeToken<PunchResponse>(){}.getType());
//        count=Integer.parseInt(punchResponse.getResult());
//        return count;
//    }

    /**
     * 订单明细数量
     * @param rv
     * @return
     */
    public int countOrderItems(Long rv) {
        int count=0;
        Gson gson = new GsonBuilder().create();
        Map<String, String> params=new HashMap<>();
        Map<String, String> headers=new HashMap<>();
        //https://pisi.punch.com.cn:8498/CRM/api/CO/Count/{rv}
        String response = okHttpUtils.doGet(punchConfig.getUrl().concat("/CRM/api/COItem/Count/"+rv.toString()), params,headers);
        PunchResponse punchResponse = gson.fromJson(response, new TypeToken<PunchResponse>(){}.getType());
        count=Integer.parseInt(punchResponse.getResult());
        return count;
    }

    private int countEmployees(Long rv) {
        int count=0;
        Gson gson = new GsonBuilder().create();
        Map<String, String> params=new HashMap<>();
        Map<String, String> headers=new HashMap<>();
        //https://pisi.punch.com.cn:8498/CRM/api/CO/Count/{rv}
        String response = okHttpUtils.doGet(punchConfig.getUrl().concat("/CRM/api/hr/emp/count/"+rv.toString()), params,headers);
        PunchResponse punchResponse = gson.fromJson(response, new TypeToken<PunchResponse>(){}.getType());
        count=Integer.parseInt(punchResponse.getResult());
        return count;
    }


//    public ResponseVo getOrderItemList(Long rv) {
//        //为空则到表中取
//        if (rv==null) {
//            //1=punch_sales_client
//            rv=getMaxRvid("3");
//        }
//        Gson gson = new GsonBuilder().create();
//        Map<String, String> params=new HashMap<>();
////        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
////        params.put("startDate", startDate);
////        params.put("endDate",endDate);
//        Map<String, String> headers=new HashMap<>();
//        //每页条数
//        int sz=10;
//        //页面
//        int pg=1;
//        //记录总数
//        int maxCount=this.countOrderItems(rv);
//        log.info("最大记录数maxCount:{}",maxCount);
//        //测试，先默认
//        maxCount=130;
//        // 计算总页数 (向上取整)
//        int totalPages = (int) Math.ceil((double) maxCount / sz);
//        for (int currentPage = pg; currentPage <= totalPages; currentPage++) {
//            //https://pisi.punch.com.cn:8498/CRM/api/CO/{rv}/{sz}/{pg}
//            String response = okHttpUtils.doGet(punchConfig.getUrl().concat("/CRM/api/COItem/"+rv.toString()+"/"+sz+"/"+currentPage), params,headers);
//            PunchResponse punchResponse = gson.fromJson(response, new TypeToken<PunchResponse>(){}.getType());
//            //String result =punchResponse.getResult();
//            List<PunchOrderItemResponseEntity> list = gson.fromJson(punchResponse.getResult(), new TypeToken<List<PunchOrderItemResponseEntity>>(){}.getType());
//            for(PunchOrderItemResponseEntity punchOrderItemResponseEntity:list){
//               // saveOrUpdateOrderItem(punchOrderItemResponseEntity);
//            }
//
//            // 如果已经是最后一页，退出循环
//            if (currentPage == totalPages) {
//                break;
//            }
//        }
//
//        return ResponseVo.ok().setData(maxCount);
//    }



}
